package com.hnblc.blcwms.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnblc.blcwms.common.interaction.Response;
import com.hnblc.blcwms.common.utils.WmsTimeUtils;
import com.hnblc.blcwms.persistent.business.basedefine.entity.Article;
import com.hnblc.blcwms.persistent.business.basedefine.service.IArticleService;
import com.hnblc.blcwms.persistent.business.odata.service.IOdataExpDService;
import com.hnblc.blcwms.persistent.business.odata.vo.ExpDeliveryInfoVO;
import com.hnblc.blcwms.persistent.business.odata.vo.ExpressQueryVO;
import com.hnblc.blcwms.persistent.interfaces.business.entity.WmsRetration;
import com.hnblc.blcwms.persistent.interfaces.business.service.IErpExpStatusService;
import com.hnblc.blcwms.persistent.interfaces.business.service.IWmsRetrationService;
import com.hnblc.blcwms.persistent.interfaces.client.entity.ClientAuth;
import com.hnblc.blcwms.serviceapi.api.dto.untread.UntreadBody;
import com.hnblc.blcwms.serviceapi.api.dto.untread.UntreadHead;
import com.hnblc.blcwms.serviceapi.api.enums.code.UntreadEntireEnum;
import com.hnblc.blcwms.serviceapi.api.enums.code.UntreadQualityEnum;
import com.hnblc.blcwms.serviceapi.api.enums.code.UntreadTypeEnum;
import com.hnblc.blcwms.serviceapi.api.enums.result.businiss.UntreadResultEnum;
import com.hnblc.blcwms.serviceapi.api.service.IUntreadAPIService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@Service
public class UntreadAPIService implements IUntreadAPIService {

    @Autowired
    IWmsRetrationService wmsRetrationService;
    @Autowired
    IErpExpStatusService erpExpStatusService;

    //TODO 此处访问业务库
    @Autowired
    IOdataExpDService odataExpDService;

    @Autowired
    IArticleService articleService;
    @Override
    public Response<UntreadBody> createReturnNote(UntreadHead untreadHead, ClientAuth clientAuth) {
        //判断良品类型是否存在
        boolean typeExist = false;
        for (UntreadQualityEnum qualityEnum: UntreadQualityEnum.values()){
            if (qualityEnum.code().equalsIgnoreCase(untreadHead.getQualityType())){
                typeExist = true;
            }
        }
        if (!typeExist){
            return new Response<>(UntreadResultEnum.CREATE_ERROR_WRONG_QUALITY_TYPE);
        }
        if (UntreadTypeEnum.B2C.code().equalsIgnoreCase(untreadHead.getPoType())){
            return this.createOnLineReturnNote(untreadHead,clientAuth);
        }else if (UntreadTypeEnum.B2B.code().equalsIgnoreCase(untreadHead.getPoType())){
            return this.createOffLineReturnNote(untreadHead,clientAuth);
        }else
            return new Response<>(UntreadResultEnum.CREATE_ERROR_WRONG_TYPE);

    }


    private Response<UntreadBody> createOnLineReturnNote(UntreadHead untreadHead, ClientAuth clientAuth) {


        //验证是否填写原订单号或原单号其中一项
        if (StringUtils.isEmpty(untreadHead.getPoOrderNo()) && StringUtils.isEmpty(untreadHead.getPoLogisticNo()))
            return new Response<>(UntreadResultEnum.CREATE_ERROR_WRONG_RETURN_WAY);
        //加载原订单信息
        ExpressQueryVO expParam = new ExpressQueryVO();
        expParam.setEnterpriseNo(clientAuth.getEnterpriseNo());
        expParam.setWarehouseNo(clientAuth.getWarehouseNo());
        expParam.setOwnerNo(clientAuth.getOwnerNo());
        expParam.setCustNo(clientAuth.getCustomNo());
        expParam.setSourceexpNo(untreadHead.getPoOrderNo());
        expParam.setShipperDeliverNo(untreadHead.getPoLogisticNo());
        List<ExpDeliveryInfoVO> odataDetails= odataExpDService.getExpDWithExpM(expParam);
        //原订单号或运单号不存在
        if (odataDetails.size()<1)
            return new Response<>(UntreadResultEnum.CREATE_ERROR_SHEET_NO_NOT_FOUND);

        //构造退货通知单
        List<WmsRetration> retrations = new ArrayList<>();

        if (UntreadEntireEnum.ENTIRE.code().equalsIgnoreCase(untreadHead.getEntireFlag())){//整单退货
            odataDetails.forEach(item -> {
                // 根据查询结果构造要保存的退货单
                retrations.add(this.buildWmsRetrationFromOrder(item,untreadHead));
            });
        }else {//部分退货
            //判断是否填充内件信息
            if (untreadHead.getUntreadBodyList().size()<1)
                return new Response<>(UntreadResultEnum.CREATE_ERROR_PRODUCT_NOT_FOUND);
            //循环填充
            for (UntreadBody untreadBody:untreadHead.getUntreadBodyList()){
                // 根据查询结果构造要保存的退货单
                int count=0;
                for (ExpDeliveryInfoVO expDetailVO:odataDetails) {
                    if (expDetailVO.getOwnerArticleNo().equalsIgnoreCase(untreadBody.getOwnerArticleNo())) {
                        count++;
                        if (expDetailVO.getPlanQty() >= untreadBody.getPlanQty()) //判断数量是否超量
                            retrations.add(this.buildWmsRetration(expDetailVO, untreadBody, untreadHead));
                        else{
                            untreadBody.setErrorReason(UntreadResultEnum.CREATE_ERROR_PRODUCT_BEYOND_AMOUNT.getMessage());
                            return new Response<>(UntreadResultEnum.CREATE_ERROR_PRODUCT_BEYOND_AMOUNT, untreadBody);
                        }
                    }
                }
                if (count == 0) {
                    untreadBody.setErrorReason(UntreadResultEnum.CREATE_ERROR_WRONG_PRODUCT.getMessage());
                    return new Response<>(UntreadResultEnum.CREATE_ERROR_WRONG_PRODUCT, untreadBody);
                }
            }
        }


        //批量保存退货单
        if (!wmsRetrationService.saveBatch(retrations)){
            return new Response<>(UntreadResultEnum.CREATE_ERROR_UNKNOWN);
        }


        return new Response<>(UntreadResultEnum.CREATE_SUCCESS);
    }

    private WmsRetration buildWmsRetrationFromOrder(ExpDeliveryInfoVO odataDetail, UntreadHead untreadHead){

        WmsRetration wmsRetration = new WmsRetration();
        wmsRetration.setCustomid(odataDetail.getOwnerNo());
        wmsRetration.setShopNo("A0000L");
        wmsRetration.setShopid(odataDetail.getCustNo());
        wmsRetration.setGoodsid(odataDetail.getOwnerArticleNo());
        wmsRetration.setPalletzone(odataDetail.getWarehouseNo());
        wmsRetration.setNotes(untreadHead.getRemark());
        wmsRetration.setPlanqty(odataDetail.getPlanQty());
        wmsRetration.setPkcount(odataDetail.getPackingQty());
        wmsRetration.setRtype(Double.valueOf(untreadHead.getPoType()));
        wmsRetration.setSdate(WmsTimeUtils.parseTime(untreadHead.getReturnDate()));
        wmsRetration.setSheetid(odataDetail.getSourceexpNo());
        wmsRetration.setErpReturnNo(untreadHead.getReturnErpNo());
        wmsRetration.setSerialid(odataDetail.getRowId());
        wmsRetration.setQualityType(untreadHead.getQualityType());
        return wmsRetration;
    }

    private WmsRetration buildWmsRetration(ExpDeliveryInfoVO odataDetail, UntreadBody untreadBody, UntreadHead untreadHead){
        WmsRetration wmsRetration = new WmsRetration();
        wmsRetration.setPalletzone(odataDetail.getWarehouseNo());
        wmsRetration.setCustomid(odataDetail.getOwnerNo());
        wmsRetration.setShopNo("A0000L");
        wmsRetration.setShopid(odataDetail.getCustNo());
        wmsRetration.setGoodsid(untreadBody.getOwnerArticleNo());
        wmsRetration.setNotes(untreadHead.getRemark());
        wmsRetration.setPlanqty(untreadBody.getPlanQty());
        wmsRetration.setPkcount(odataDetail.getPackingQty());
        wmsRetration.setRtype(Double.valueOf(untreadHead.getPoType()));
        wmsRetration.setQualityType(untreadHead.getQualityType());
        wmsRetration.setSdate(WmsTimeUtils.parseTime(untreadHead.getReturnDate()));
        wmsRetration.setSheetid(odataDetail.getSourceexpNo());
        wmsRetration.setErpReturnNo(untreadHead.getReturnErpNo());
        wmsRetration.setSerialid(odataDetail.getRowId());
        return wmsRetration;
    }


    /**
     * 创建线下退配通知单
     * @param untreadHead 退配单实体
     * @param clientAuth 对应操作权限
     * @return
     */
    private Response<UntreadBody> createOffLineReturnNote(UntreadHead untreadHead, ClientAuth clientAuth) {

        //构造退货通知单
        List<WmsRetration> retrations = new ArrayList<>();

        //判断是否填充内件信息
        if (untreadHead.getUntreadBodyList().size()<1)
            return new Response<>(UntreadResultEnum.CREATE_ERROR_PRODUCT_NOT_FOUND);
        //循环填充
        for (UntreadBody untreadBody:untreadHead.getUntreadBodyList()){
            // 根据查询结果构造要保存的退货单
            Article article = articleService.getOne(new QueryWrapper<Article>().eq("owner_article_no",untreadBody.getOwnerArticleNo()));

            if (article==null)
                return new Response<>(UntreadResultEnum.CREATE_ERROR_ARTICLE_NOT_FOUND,new Object[]{untreadBody.getOwnerArticleNo()});

            retrations.add(this.buildShopWmsRetration(untreadBody,untreadHead,clientAuth));
        }

        //批量保存退货单
        if (!wmsRetrationService.saveBatch(retrations)){
            return new Response<>(UntreadResultEnum.CREATE_ERROR_UNKNOWN);
        }


        return new Response<>(UntreadResultEnum.CREATE_SUCCESS);
    }
    private WmsRetration buildShopWmsRetration(UntreadBody untreadBody, UntreadHead untreadHead,ClientAuth clientAuth){
        WmsRetration wmsRetration = new WmsRetration();
        wmsRetration.setPalletzone(clientAuth.getWarehouseNo());
        wmsRetration.setCustomid(clientAuth.getOwnerNo());
        wmsRetration.setShopNo("A0000L");
        wmsRetration.setShopid(clientAuth.getCustomNo());
        wmsRetration.setGoodsid(untreadBody.getOwnerArticleNo());
        wmsRetration.setNotes(untreadHead.getRemark());
        wmsRetration.setPlanqty(untreadBody.getPlanQty());
        wmsRetration.setPkcount(untreadBody.getPackageQty());
        wmsRetration.setRtype(Double.valueOf(untreadHead.getPoType()));
        wmsRetration.setQualityType(untreadHead.getQualityType());
        wmsRetration.setSdate(WmsTimeUtils.parseTime(untreadHead.getReturnDate()));
        wmsRetration.setSheetid(untreadHead.getReturnErpNo());
        wmsRetration.setErpReturnNo(untreadHead.getReturnErpNo());
        wmsRetration.setSerialid(untreadBody.getItemIndex().doubleValue());
        return wmsRetration;
    }
}
